﻿using Minecraft.Config;
using Minecraft.Config.ipConst;
using Minecraft.Model;
using Minecraft.Model.ReqResp;
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Protocol;
using System;
using System.Linq;
using System.Text;

namespace Minecraft.ServerHall
{
	public class MinecraftSession : AppSession<MinecraftSession>
	{
		/// <summary>
		/// minecraft session info ext
		/// </summary>
		public MinecraftSessionInfo minecraftSessionInfo = new MinecraftSessionInfo();

		protected override void OnSessionStarted()
		{
			//进入连接
			this.Logger.Info($"进入连接：{this.RemoteEndPoint.ToString()}");

			if (JsonConfig.Value.IsConsoleWrite)
			{
				string ipUserNameTipStr = IpConstConfig.GetIpUserNameTipStr(this.RemoteEndPoint.Address.ToString());
				if (!ipUserNameTipStr.IsNullOrWhiteSpace())
				{
					Console.ForegroundColor = ConsoleColor.Gray;
				}
				else
				{
					Console.ForegroundColor = ConsoleColor.DarkYellow;
				}
				Console.WriteLine();
				Console.Write($"->->->有新客户端进入：");
				Console.WriteLine($"	{this.GetOutputStr(EnumCommand.Conn_Success)}");
				Console.ResetColor();
			}
			this.Send(EnumCommand.Conn_Success, new BaseReq(), new BaseResp { RespLevel = RespLevelEnum.Success, Msg = $"Welcome to {this.AppServer.Config.Name}" });
		}

		protected override void OnSessionClosed(CloseReason reason)
		{
			//断开连接
			this.Logger.Info($"断开连接：{this.RemoteEndPoint.ToString()}");

			if (JsonConfig.Value.IsConsoleWrite)
			{
				string ipUserNameTipStr = IpConstConfig.GetIpUserNameTipStr(this.RemoteEndPoint.Address.ToString());
				if (!ipUserNameTipStr.IsNullOrWhiteSpace())
				{
					Console.ForegroundColor = ConsoleColor.DarkGray;
				}
				else
				{
					Console.ForegroundColor = ConsoleColor.DarkMagenta;
				}
				Console.WriteLine();
				Console.Write($"<-<-<-客户端断开连接：");



			    Console.WriteLine($"	{this.GetOutputStr(EnumCommand.Conn_Close)}		（CloseReason：{reason.ToString()}）");
				Console.WriteLine();
				Console.ResetColor();
			}

			//保存数据
			this.SaveData();
		}

		//服务器发送给客户端的消息的后续处理方法
		protected override string ProcessSendingMessage(string rawMessage)
		{
			//加密处理，加上 数据结尾分隔符，用作黏包情况处理
			var str = EncryptHelper.Encrypt(rawMessage) + SeparatorConfig.StickyBag;
			var bytes = CommonConfig.DefEncoding.GetBytes(str);
			return SeparatorConfig.DataPacketHead + bytes.Count() + SeparatorConfig.DataPacketHead + str;
		}

		protected override void HandleException(Exception ex)
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendLine($"服务器错误：");
			stringBuilder.AppendLine($"{this.GetOutputStr(EnumCommand.Handle_HandleException)}");
			stringBuilder.AppendLine($"{ex.ToString()}");
			string exceptionStr = stringBuilder.ToString();
			this.Logger.Fatal(exceptionStr);
			if (JsonConfig.Value.IsConsoleWrite)
			{
				Console.WriteLine(exceptionStr);
			}
			this.Send(EnumCommand.Handle_HandleException, new BaseReq(), new BaseResp { RespLevel = RespLevelEnum.Error, Msg = ex.Message });
			this.Close(CloseReason.ApplicationError);
		}

		protected override void HandleUnknownRequest(StringRequestInfo requestInfo)
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendLine($"客户端未知请求：");
			stringBuilder.AppendLine($"{this.GetOutputStr(EnumCommand.Handle_HandleUnknownRequest)}");
			string str = stringBuilder.ToString();
			this.Logger.Fatal(str);
			if (JsonConfig.Value.IsConsoleWrite)
			{
				Console.WriteLine(str);
			}
			this.Send(EnumCommand.Handle_HandleUnknownRequest, new BaseReq(), new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"Unknow request：{requestInfo.Key}" });
			this.Close(CloseReason.ProtocolError);
		}
	}
}
